import { AutoCenter, Button, DotLoading, Grid, Modal, Popup, Toast, Space } from "antd-mobile";
import React, { useEffect, useMemo, useRef, useState } from "react";
import requewt from "@/utils/requewt";
import { API, BASE_PATH } from "@/config";
import callFeedback from "@/components/common/modalFeedback";
import { useRouter } from "next/router"
import { KvBrandComp, RuleComp, PrizeComp } from "@/components/common";
import { signIn, useSession } from "next-auth/react";
import { useCookies } from "react-cookie";
import { checkENV2, WECHAT, HC, isValidArr, reloadSession, calcCrow, navigateTo } from "@/utils";
import { motion, scroll } from "framer-motion";
import classNames from "classnames";
import Image from "next/image";
import { ResultComp } from "@/components/pages/prize";
import { CardsComponents, showGameCard, useUserCard } from "./components/GameCard";
import { FeedbackComp } from "../../wheel";
import { useCommonHandler } from "@/components/common/hooks";

export default function () {
  const [loading, setLoading] = useState(false);
  const { data: userinfo, } = useSession();

  const [cookies] = useCookies(['name']);
  const [visible, setVisible] = useState(false);
  const [status, setStatus] = useState(undefined);
  // const [user, setUser] = useState(undefined);
  const user = useRef({})
  const [data, setData] = useState(undefined);
  const [remain, setRemain] = useState(0);
  // const { userBaseCards, getUserCards } = useUserCard()
  // const [isRead, setIsRead] = useState(false)
  const [drawInfo, setDrawInfo] = useState({ total: 0, remain_num: 0 })
  const { gameCheck, activeOver } = useCommonHandler()
  const router = useRouter();

  const containerVar = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        delayChildren: 0.05,
        staggerChildren: 0.05,
      }
    },
    exit: { y: 50, opacity: 0 },
  };

  const itemVar = {
    visible: {
      x: [0, 35, 70, 100,],
      y: [0, 2, 6, 6,],
      rotate: [0, 0, 0, 0],
      opacity: [1, 1, 1, 0.7, 0],
      transition: {
        ease: `linear`,
        duration: 5,
        repeat: Infinity,
      }
    },
    exit: {
      x: -160
    }
  };

  const carVarLeft = {
    hidden: { x: `100%`, opacity: 0 },
    visible: {
      x: 0,
      opacity: 1,
      transition: {
        delay: .4
      }
    },
    exit: {
      x: `100%`
    }
  };
  /**
   * @type {import("framer-motion").MotionProps}
   */
  const carVarRight = {
    visible: {
      x: [0, -40, -100, -160],
      y: [0, 2, 8, 10],
      rotate: [0, 2, 0, 2, 0],
      transition: {
        ease: `linear`,
        duration: 5,
        repeat: Infinity,
      }
    },
    exit: {
      x: -160
    }
  };

  const qiVar = {
    hidden: { scale: 0, opacity: 0 },
    visible: {
      scale: 1,
      opacity: 1,
      transition: {
        delay: .6,
        duration: 0.3
      }
    },
  };

  const itemVerticalLeftVar = {
    hidden: { x: -50, opacity: 0 },
    visible: { x: 0, opacity: 1 },
  };

  const itemVerticalRightVar = {
    hidden: { x: 50, opacity: 0 },
    visible: { x: 0, opacity: 1 },
  };

  const titleVar = {
    hidden: { x: -100, opacity: 0 },
    visible: {
      x: 0,
      opacity: 1,
    },
  };

  const floatVar = {
    visible: {
      y: [0, 20, 0, -20, 0],
      rotate: [0, 2, 0, -2, 0],
      transition: {
        ease: `linear`,
        duration: 10,
        repeat: Infinity,
      }
    },
  };
  // useEffect(() => {
  //   if (userBaseCards.every(card => card.num > 0) && !sessionStorage.getItem('is_composite')) {
  //     sessionStorage.setItem('is_composite', 'true')
  //     navigateTo('/game')
  //   }
  // }, [userBaseCards])
  useEffect(() => {
    (async () => {
      if (!userinfo) return;
      // setUser(userinfo?.user);
      user.current = userinfo?.user

      // await handler.fetch();
    })()
  }, [userinfo])

  useEffect(() => {
    (async () => {
      console.log('fffffff')
      // await handler.check();
      // await handler.remain()
      // handler.check().then((resp) => {
      //   console.log('xxxxxxx22222222')
      //   // debugger
      //   if (!sessionStorage.getItem('is_composite') && resp.data.is_composite) {

      //     navigateTo('/game')
      //     sessionStorage.setItem('is_composite', resp.data.is_composite)
      //   }


      // })

    })()

    return () => {
      Toast.clear();
      Modal.clear()
    }
  }, [])

  const handler = {
    check: async () => {
      const resp = await requewt(API.user.userCardDrawNum)
      setDrawInfo(resp.data || {})
      if (resp.data.is_composite && !sessionStorage.getItem('is_composite')) {
        sessionStorage.setItem('is_composite', resp.data.is_composite)
        await router.push('/game')
        return {}
      }
      return resp

    },
    reward: async () => {
      const resp = await requewt(API.prize.reward);
      console.log(`resp`, resp)
      if (resp?.error_code !== 0) {
        await Toast.clear();
        await callFeedback({ title: resp?.msg || `请求失败` });
        return;
      }

      const m = callFeedback({
        bodyClassName: `act-feedback-modal cp-prize-result close-hidden`,
        content: <div className="inner">
          <ResultComp handler={handler} result={resp?.data} />
        </div>,
        actions: <>
          <Button shape={`rounded`} key={1}
            className="act-btn act-btn-bevel"
            onClick={e => m.close()}
          >
            确定
          </Button>
          {
            resp?.data?.status === 0 &&
            <Button shape={`rounded`}
              className="act-btn act-btn-bevel"
              key={2}
              onClick={e => navigateTo(`/lottery`)}
            >
              去抽奖
            </Button>
          }
        </>,
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    },

    start: async (is_robot) => {
      setVisible(false)
      /** 是否在游戏时间 */
      const resp = await requewt(API.user.userActivity)
      // const resp = {
      //   "data": null,
      //   "error_code": 999,
      //   "msg": "不在活动时间",
      //   "request": "GET /warm1118api/user/activity"
      // }
      if (resp.error_code == 999) {
        return activeOver(resp)
      }
      /** 是否有游戏次数 */
      const gameNum = await requewt(API.user.userGameNum)
      // const gameNum = {
      //   "data": {
      //     "remain_game_num": 500,
      //     "state": 3
      //   },
      //   "error_code": 0,
      //   "msg": "ok",
      //   "request": "GET /thing1120api/user/game/num"
      // }
      if (gameNum.data?.state !== 1) {
        return gameCheck(gameNum.data?.state)
      }
      // if (drawInfo.remain_num <= 0) {
      //   const resp = await requewt(API.user.qrcode)
      //   return callFeedback({
      //     bodyClassName: 'act-feedback-modal share-modal  close-at-center-bottom',
      //     content: <AutoCenter>
      //       <AutoCenter>
      //         <Space direction="vertical" align="center">
      //           <h3>邀请好友获抽卡机会</h3>
      //           <Space direction="vertical" align="center">
      //             <div>您已无抽卡机会</div>
      //             <div>赶快邀请好友入群获取抽卡次数吧</div>
      //           </Space>
      //         </Space>
      //       </AutoCenter>
      //       <AutoCenter>
      //         <img
      //           src={resp.data.qr_code}
      //           width='180'
      //           height='180'
      //           style={{ marginTop: '20px' }}
      //         />
      //       </AutoCenter>
      //       <AutoCenter>
      //         <Space direction="vertical" align="center">
      //           <h4>长按二维码，转发邀请好友</h4>

      //         </Space>
      //       </AutoCenter>
      //     </AutoCenter>,
      //     actions: [],
      //     hideClose: true
      //   })
      // }
      // const activeResp = await handler.userActive()
      // if (activeResp.error_code === 999) {
      //   return callFeedback({
      //     bodyClassName: 'act-feedback-modal prize-modal close-at-center-bottom',
      //     title: <div style={{ textAlign: 'center' }} dangerouslySetInnerHTML={{ __html: activeResp?.msg || "游戏开始失败" }}></div>,
      //     actions: [],
      //     closeOnAction: false,
      //     closeOnMaskClick: false,
      //     onClose() { }
      //   })
      // }
      handler.enter(is_robot)
    },
    enter: async (item, is_robot) => {
      // await router.push(`/game`)

      // return
      // if (!remain) {
      //   const m = callFeedback({
      //     bodyClassName: `act-feedback-modal cp-game-result close-hidden close-at-center-bottom`,
      //     content: <div className="inner">
      //       <div className="header">
      //         <img src={`${BASE_PATH}/img/game/game-result-header-fail.png`} alt="" />
      //       </div>
      //       <div className="content">
      //         <img className="img-fluid" src={`${BASE_PATH}/img/game/no-remain.png`} alt="" />
      //       </div>
      //     </div>,
      //     actions: [
      //       <Button shape={`rounded`}
      //               className="act-btn act-btn-bevel"
      //               onClick={e => {
      //                 m.close()
      //               }}
      //       >
      //         确定
      //       </Button>
      //     ]
      //   })
      //
      //   return
      // }
      // console.log(user,'user')
      // return
      console.log(user, 'userrrr')
      if (user.current.is_robot) {
        console.log('xxxxxx')
        setVisible(true);
        setTimeout(() => {
          HC(handler.humanCheck, item)
        }, 300)
        return
      }

      Toast.show({ content: `进入中`, icon: `loading`, duration: 0 });
      await router.push(`/game`)
      // window.location.href = `/landscape0925/game`
    },
    remain: async () => {
      setLoading(true);
      const resp = await requewt(API.game.remain);
      setTimeout(() => setLoading(false), 300);
      if (resp?.error_code !== 0) {
        await callFeedback({ title: resp?.msg || `请求失败` });
        return;
      }
      setRemain(resp?.data);
    },
    humanCheck: async (values, record) => {
      if (!values) return;
      const options = {
        method: `POST`,
        headers: { "Content-Type": `multipart/form-data` },
        body: values
      }
      const resp = await requewt(API.user.check, options);
      if (resp?.error_code !== 0 || resp?.[`msg`] !== `ok`) {
        await callFeedback({ title: resp?.msg || `验证失败` });
        setVisible(false)
        return;
      }

      const { auth } = cookies || {};
      await signIn("credentials", {
        token: auth, redirect: false
      });

      reloadSession()
      // setVisible(false)
      // setUser(s => {
      //   return { ...s, is_robot: false }
      // })
      user.current = { ...user.current, is_robot: false }
      handler.start()
      // setVisible(false)

      // await router.push(`/game`)
    },
    userActive: async () => {
      const resp = requewt(API.user.userActivity)
      return resp
    }
  }
  const toolbarHandle = {
    // 打开规则
    rule: (options) => {
      const m = callFeedback({
        bodyClassName: `rule-modal close-at-center-bottom`,
        // title: <img className="header-img" src={`${BASE_PATH}/img/rule/rule-title.png`} alt="" />,
        title: <div>活动规则</div>,
        content: <div className="inner" onScroll={() => {
        }}><RuleComp /></div>,
        actions: <></>,
        closeOnAction: true,
        closeOnMaskClick: true,
        ...options
      })

      // if (!isRead) {
      //   setTimeout(() => {
      //     console.log(document.querySelector('.rule-modal .content .inner'),'cvvv')
      //     if (isRead) return
      //     document.querySelector('.rule-modal .content').addEventListener('scroll', ({target}) => {
      //       // console.log(target,'target')

      //       if (target.scrollHeight - target.scrollTop === target.clientHeight) {
      //         setIsRead(true)
      //       }
      //     // document.querySelector('.cp-modal-content').addEventListener('scroll', () => {
      //       console.log('scroll')
      //     })
      //   //   .onscroll = 
      //   }, 200);
      // }

    },
    // 我的奖品
    prize: async () => {
      const m = callFeedback({
        bodyClassName: `act-feedback-modal prize-modal close-at-center-bottom`,
        content: <div className="inner"><PrizeComp /></div>,
        title: <div>我的奖品</div>,
        actions: <>

        </>,
        closeOnAction: true,
        closeOnMaskClick: true,
      })
    },
  }

  return (
    <>
      {/* <KvBrandComp /> */}

      <div className="deco-wrapper share-page">
        <motion.div className="inner"
          variants={containerVar}
          initial="hidden"
          animate="visible"
          exit="exit"
        >


        </motion.div>
        {/* {
          hasAll && <div style={{ position: 'absolute', bottom: '3vh', left: '50%', transform: 'translateX(-50%)' }}><AutoCenter><Button className="act-btn act-btn-bevel act-btn-warning">立即合成</Button></AutoCenter></div>
        } */}
      </div>

      <div className="landing-footer">
        <AutoCenter>
          <Button style={{ fontWeight: 'bold' }} className={`home-btn act-btn act-btn-bevel`} onClick={handler.start}>
            开启挑战
          </Button>
        </AutoCenter>
        <AutoCenter style={{ marginTop: '20px' }}>
          <Button style={{ fontWeight: 'bold' }} className={`home-btn act-btn act-btn-bevel`} onClick={() => navigateTo('/rank/current')}>
            智电值排行榜
          </Button>
        </AutoCenter>
      </div>



      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false)
        }}
        position='bottom'
        destroyOnClose={true}
      >
        <div className="human-check">
          <div className="title">安全验证</div>
          <div id="nc" />
        </div>
      </Popup>

    </>
  )
}
